package org.xx.armory.spring5.jpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.xx.armory.commons.ForLogging;
import org.xx.armory.spring5.junit.DbUnitHelper;
import org.xx.armory.spring5.junit.H2DbUnitHelper;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * JPA测试相关的Bean配置。
 */
@SpringBootConfiguration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        basePackages = {"org.xx.armory.spring5.jpa"}
)
public class Config {
    @ForLogging
    private final Logger logger = LoggerFactory.getLogger(Config.class);

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            DataSource dataSource
    ) {
        return builder
                .dataSource(dataSource)
                .packages("org.xx.armory.spring5.jpa")
                .build();
    }

    @Bean
    public PlatformTransactionManager transactionManager(
            EntityManagerFactory entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean
    public DbUnitHelper dbUnitHelper() {
        return new H2DbUnitHelper();
    }

    @Bean
    public BookProvider bookProvider() {
        return new BookProvider();
    }
}
